from flask import Blueprint, request, jsonify, current_app
import os
import traceback
from datetime import datetime

# 确保导入路径正确
from app.server.lstm_model import LSTMForecaster

# 修改Blueprint名称确保唯一性
predict_lstm_bp = Blueprint('predict_lstm_bp', __name__, url_prefix='/api')

@predict_lstm_bp.route('/predict_lstm', methods=['GET'])
def lstm_predict():
    """LSTM预测接口"""
    try:
        # 获取参数
        target_col = request.args.get('target', 'guilin_temp')
        days = int(request.args.get('days', 90))

        # 初始化预测器
        current_app.logger.info("初始化LSTMForecaster...")
        forecaster = LSTMForecaster(target_col=target_col)

        # 加载数据
        current_app.logger.info("加载数据...")
        forecaster.train_test_split(test_size=0.2)

        # 构建和加载模型
        current_app.logger.info("构建模型...")
        forecaster.build_model()

        model_path = './app/saved_models/LSTM/best_model.h5'
        if os.path.exists(model_path):
            current_app.logger.info(f"加载模型权重: {model_path}")
            forecaster.load_model(model_path)
        else:
            current_app.logger.warning(f"模型文件不存在: {model_path}")
            return jsonify({
                'status': 'error',
                'message': f'模型文件不存在: {model_path}'
            }), 404

        # 执行预测
        current_app.logger.info(f"预测未来{days}天...")
        predictions = forecaster.forecast(days=days)  # 注意这里改为forecast方法

        return jsonify({
            'status': 'success',
            'predictions': predictions['predictions'],
            'plot_url': predictions.get('plot_url', ''),
            'last_training_date': predictions.get('last_training_date'),
            'execution_time': datetime.now().isoformat()
        })

    except Exception as e:
        current_app.logger.error(f"预测失败: {traceback.format_exc()}")
        return jsonify({
            'status': 'error',
            'message': str(e),
            'traceback': traceback.format_exc()
        }), 500